/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on May 10, 2011, 2:14:58 PM
 */

package c0907m.group2.aitsm.gui;

import c0907m.group2.aitsm.core.db.UserDb;
import c0907m.group2.aitsm.core.entity.UserInfo;
import c0907m.group2.aitsm.gui.component.StatusBar;
import c0907m.group2.aitsm.gui.handler.LoggedInEvent;
import c0907m.group2.aitsm.gui.handler.LoggedInListener;
import c0907m.group2.aitsm.util.Helper;
import c0907m.group2.aitsm.util.Settings;

import javax.swing.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author ISTC
 */
public class Login extends javax.swing.JPanel {
    private UserInfo loginUser;
    private StatusBar statusBar;
    public final Logger logger = Logger.getLogger(Login.class.getName());


    /**
     * Creates new form Login
     */
    public Login() {
        initComponents();
        checkSettings();
    }

    public void setStatusBar(StatusBar sb) {
        statusBar = sb;
    }

    /**
     * Return the default button for root pane
     *
     * @return default button
     */
    public JButton getDefaultButton() {
        return btnLogin;
    }

    public UserInfo getLoginUser() {
        return loginUser;
    }

    /**
     * Register for LoggedInEvent
     *
     * @param l a listener of LoggedInEvent
     */
    public void addLoggedInListener(LoggedInListener l) {
        listenerList.add(LoggedInListener.class, l);
    }

    /**
     * Unregister for LoggedInEvent
     *
     * @param l a listener of LoggedInEvent
     */
    public void removeLoggedInListener(LoggedInListener l) {
        listenerList.remove(LoggedInListener.class, l);
    }

    /**
     * Fire a LoggedInEvent
     *
     * @param evt a fired LoggedInEvent
     */
    private void fireLoggedInEvent(LoggedInEvent evt) {
        Object[] listeners = listenerList.getListenerList();

        for (int i = 0; i < listeners.length; i += 2) {
            if (listeners[i] == LoggedInListener.class) {
                ((LoggedInListener) listeners[i + 1]).loggedIn(evt);
            }
        }
    }

    /**
     * Check saved settings
     */
    private void checkSettings() {
        if (Integer.parseInt(Helper.PROPS.getProperty("loginInfoSave")) == 1) {
            txtUserName.setText(Helper.PROPS.getProperty("userName"));
        }
    }

    /**
     * Login to system
     */
    private void doLogin() {
        if (!txtUserName.getText().trim().toLowerCase().matches("^\\w+([-.]\\w+)*@\\w+([-.]\\w+)*.\\w+$")) {
            JOptionPane.showMessageDialog(
                    this,
                    "Invalid username or password.",
                    "Message",
                    JOptionPane.INFORMATION_MESSAGE
            );
            return;
        }

        List<UserInfo> list = new ArrayList<UserInfo>();
        try {
            list = new UserDb().select(txtUserName.getText().trim());
            if (list.isEmpty()) {
                JOptionPane.showMessageDialog(
                        this,
                        "Invalid username or password.",
                        "Message",
                        JOptionPane.INFORMATION_MESSAGE
                );
                return;
            }

            for (UserInfo ui : list) {
                if (!ui.getPassword().equals(Helper.MD5(String.copyValueOf(jpfPassword1.getPassword())))
                        || !ui.isActive()) {
                    JOptionPane.showMessageDialog(
                            this,
                            "Invalid username or password.",
                            "Message",
                            JOptionPane.INFORMATION_MESSAGE
                    );
                    return;
                }
                loginUser = ui;
            }
            if (cbSave.isSelected()) {
                Helper.PROPS.setProperty("loginInfoSave", "1");
                Helper.PROPS.setProperty("userName", txtUserName.getText());
            } else {
                Helper.PROPS.setProperty("loginInfoSave", "0");
            }
            Helper.saveSettings();
            fireLoggedInEvent(new LoggedInEvent(this));
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, null, ex);
            statusBar.setMessage("Cannot connect to server", StatusBar.ERROR_TYPE);
        }
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel8 = new javax.swing.JLabel();
        lblTitle = new javax.swing.JLabel();
        lblUser = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        lblPassword = new javax.swing.JLabel();
        jpfPassword1 = new javax.swing.JPasswordField();
        btnLogin = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();
        cbSave = new javax.swing.JCheckBox();

        setBackground(new java.awt.Color(255, 255, 255));

        jLabel8.setBackground(new java.awt.Color(255, 255, 255));
        jLabel8.setIcon(new ImageIcon(Settings.IMAGES_DIR + "/login.png"));
        jLabel8.setName("lblLoginLogo"); // NOI18N

        lblTitle.setFont(new java.awt.Font("Tahoma", 1, 11));
        lblTitle.setText("Please login to system:");
        lblTitle.setName("lblTitle"); // NOI18N

        lblUser.setText("Email:");
        lblUser.setToolTipText("");
        lblUser.setName("lblUser"); // NOI18N

        txtUserName.setName("txtUser"); // NOI18N

        lblPassword.setText("Password:");
        lblPassword.setName("lblPassword"); // NOI18N

        jpfPassword1.setName("jpfPassword"); // NOI18N
        jpfPassword1.setVerifyInputWhenFocusTarget(false);

        btnLogin.setIcon(new ImageIcon(Settings.IMAGES_DIR + "/login_btn.png"));
        btnLogin.setText("Login");
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });

        btnExit.setIcon(new ImageIcon(Settings.IMAGES_DIR + "/exit_btn.png"));
        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        cbSave.setBackground(new java.awt.Color(255, 255, 255));
        cbSave.setSelected(true);
        cbSave.setText("Remember user ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 475, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addGap(5, 5, 5)
                                        .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGroup(layout.createSequentialGroup()
                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                .addComponent(lblPassword)
                                                                .addComponent(lblUser))
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                                .addComponent(txtUserName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                                                                .addComponent(jpfPassword1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                                                                .addGroup(layout.createSequentialGroup()
                                                                        .addComponent(btnLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE)
                                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                        .addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                        .addGap(54, 54, 54))
                                                                .addComponent(cbSave, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))))
                                        .addGap(5, 5, 5)))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 179, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addContainerGap()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(layout.createSequentialGroup()
                                                        .addComponent(lblTitle)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(lblUser)
                                                                .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(lblPassword)
                                                                .addComponent(jpfPassword1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                        .addGap(7, 7, 7)
                                                        .addComponent(cbSave)
                                                        .addGap(40, 40, 40))
                                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(btnLogin)
                                                                .addComponent(btnExit))))
                                        .addContainerGap(22, Short.MAX_VALUE))
                                .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        doLogin();
    }//GEN-LAST:event_btnLoginActionPerformed

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        try {
            Config.connection.close();
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, null, ex);
        } finally {
            System.exit(0);
        }
    }//GEN-LAST:event_btnExitActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnLogin;
    private javax.swing.JCheckBox cbSave;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPasswordField jpfPassword1;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JLabel lblUser;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables

}
